package com.rxt.thermopro.viewmodel

import android.util.SparseArray
import androidx.core.util.isEmpty
import androidx.core.util.set
import com.app.common.ex.logD
import com.app.common.viewmodel.BaseViewModel
import com.app.common.viewmodel.EventLiveData
import com.rxt.ble.BleManager
import com.rxt.ble.callback.BleWriteCallback
import com.rxt.ble.data.BleDevice
import com.rxt.ble.exception.BleException
import com.rxt.ble.utils.HexUtil
import com.rxt.thermopro.bean.EventAlarmTextData
import com.rxt.thermopro.bean.ProfileBean

class BBQViewModel : BaseViewModel() {

    companion object {
        const val BLUETOOTH_SERVICE_UUID = "0000fff0-0000-1000-8000-00805f9b34fb"
        const val BLUETOOTH_NOTIFY_UUID = "0000fff2-0000-1000-8000-00805f9b34fb"
        const val BLUETOOTH_WRITE_UUID = "0000fff1-0000-1000-8000-00805f9b34fb"
    }

    val alarmClockText1: EventLiveData<HashMap<Long, EventAlarmTextData>> = EventLiveData()
    val alarmClockText2: EventLiveData<HashMap<Long, EventAlarmTextData>> = EventLiveData()
    val alarmClockText3: EventLiveData<HashMap<Long, EventAlarmTextData>> = EventLiveData()
    val alarmClockText4: EventLiveData<HashMap<Long, EventAlarmTextData>> = EventLiveData()

    val compute2TempTime:EventLiveData<HashMap<String, String>> = EventLiveData()

    /**
     * 查询设备状态
     */
    fun getDeviceInfo(device: BleDevice) {
        val msg = "aabb01bcff"
        val deviceList = BleManager.getInstance().allConnectedDevice
        if (deviceList.isNotEmpty()) {
            BleManager.getInstance().write(
                device,
                BLUETOOTH_SERVICE_UUID,
                BLUETOOTH_WRITE_UUID,
                HexUtil.hexStringToBytes(msg),
                object : BleWriteCallback() {
                    override fun onWriteSuccess(
                        current: Int,
                        total: Int,
                        justWrite: ByteArray
                    ) {
                        // 发送数据到设备成功
                        logD(" 蓝牙发送数据成功")

                    }

                    override fun onWriteFailure(exception: BleException) {
                        logD(" 蓝牙发送数据失败  ${exception.toString()}")
                        // 发送数据到设备失败

                    }
                })
        }
    }

    fun setDeviceInfo() {
        val msg = "aacc0032ffff003200140032001400320014ceff"
        val deviceList = BleManager.getInstance().allConnectedDevice
        if (deviceList.isNotEmpty()) {
            BleManager.getInstance().write(
                deviceList[0],
                BLUETOOTH_SERVICE_UUID,
                BLUETOOTH_WRITE_UUID,
                HexUtil.hexStringToBytes(msg),
                object : BleWriteCallback() {
                    override fun onWriteSuccess(
                        current: Int,
                        total: Int,
                        justWrite: ByteArray
                    ) {
                        // 发送数据到设备成功
                        logD(" 蓝牙发送数据成功  $msg")

                    }

                    override fun onWriteFailure(exception: BleException) {
                        logD(" 蓝牙发送数据失败  ${exception.toString()}")
                        // 发送数据到设备失败

                    }
                })
        }
    }

    fun setProfile(profileArray: SparseArray<ProfileBean>, address: String,deviceType:Int) {
        println("profileArray====$profileArray")
        if (profileArray.isEmpty()) {
            return
        }
        val size=if (deviceType== BleMessageViewModel.DEVICE_TYPE_BBQ) 4 else 2
//        val size=4
        val hexList = SparseArray<String>(size)
        for (i in 0 until size) {
            if (profileArray[i].singleTemp) {
                val num = profileArray[i].highTemperatureNum.replace("°C", "")
                    .toInt()
                var numStr = Integer.toHexString(num)
                when (numStr.length) {
                    1 -> numStr = "000$numStr"
                    2 -> numStr = "00$numStr"
                    3 -> numStr = "0$numStr"
                }
                hexList[i] = numStr + "ffff"
            } else if (profileArray[i].highTemperatureNum.isEmpty() && profileArray[i].lowTemperatureNum.isEmpty()) {
                hexList[i] = "0fff0fff"
            } else {
                val num = profileArray[i].highTemperatureNum.replace("°C", "")
                    .toInt()
                var numStr = Integer.toHexString(num)
                when (numStr.length) {
                    1 -> numStr = "000$numStr"
                    2 -> numStr = "00$numStr"
                    3 -> numStr = "0$numStr"
                }
                val num1 = profileArray[i].lowTemperatureNum.replace("°C", "")
                    .toInt()
                var numStr1 = Integer.toHexString(num1)
                when (numStr1.length) {
                    1 -> numStr1 = "000$numStr1"
                    2 -> numStr1 = "00$numStr1"
                    3 -> numStr1 = "0$numStr1"
                }
                hexList[i] = numStr + numStr1
            }
        }
        println("hexList====$hexList")
        val msgSB = StringBuilder()
        var sumStr = "aacc"
        for (i in 0 until hexList.size()) {
            sumStr += hexList[i]
        }
        msgSB.append(sumStr)
        var sum = 0L
        for (i in sumStr.indices) {
            if (i % 2 == 0) {
                sum += (sumStr[i].toString() + sumStr[i + 1].toString()).toLong(16)
            }
        }
        val hexStr = Integer.toHexString(sum.toInt())
        msgSB.append(hexStr.substring(hexStr.length - 2, hexStr.length))
        msgSB.append("ff")
//        val msg = "aacc0032ffff003200140032001400320014ceff"
        val msg = msgSB.toString()
        println("setProfile msg====$msg")
        val deviceList = BleManager.getInstance().allConnectedDevice.filter { it.mac == address }
        if (deviceList.isNotEmpty()) {
            BleManager.getInstance().write(
                deviceList[0],
                BLUETOOTH_SERVICE_UUID,
                BLUETOOTH_WRITE_UUID,
                HexUtil.hexStringToBytes(msg),
                object : BleWriteCallback() {
                    override fun onWriteSuccess(
                        current: Int,
                        total: Int,
                        justWrite: ByteArray
                    ) {
                        // 发送数据到设备成功
                        logD(" 蓝牙发送数据成功 setProfile  $msg")

                    }

                    override fun onWriteFailure(exception: BleException) {
                        logD(" 蓝牙发送数据失败 $msg  ${exception.toString()}")
                        // 发送数据到设备失败

                    }
                })
        }
    }

}